// MyReact.js

// 创建虚拟 DOM函数
export function createElement(type, props, ...children) {
  return { type, props: { ...props, children } };
}

// 实现渲染函数
export function render(element, container) {
  renderFunction = () => render(element, container); // 存储渲染函数以便状态更新时调用
  while (container.firstChild) {
      container.removeChild(container.firstChild);
  }
  renderElement(element, container);
}

// 将渲染逻辑分离为 renderElement 函数
function renderElement(element, container) {
  if (typeof element === 'string' || typeof element === 'number') {
      container.appendChild(document.createTextNode(element));
      return;
  }

  if (typeof element.type === 'function') {
      const component = element.type;
      const renderedElement = component(element.props);
      renderElement(renderedElement, container);
      return;
  }

  const dom = document.createElement(element.type);

  Object.keys(element.props)
      .filter(key => key !== 'children')
      .forEach(name => {
          dom[name] = element.props[name];
      });

  element.props.children.forEach(child =>
      renderElement(child, dom)
  );

  container.appendChild(dom);
}

let globalState = {};
let renderFunction = null;

// 实现 useState
export function useState(initialValue) {
  const stateSymbol = Symbol(); // 为每个状态创建一个唯一标识
  globalState[stateSymbol] = globalState[stateSymbol] || initialValue;

  const setState = newValue => {
      globalState[stateSymbol] = newValue;
      renderFunction();
  };

  return [globalState[stateSymbol], setState];
}

// 实现 useEffect
let effects = [];
let cleanups = [];

// 实现 useEffect
export function useEffect(effect) {
    effects.push(effect);
}

// 在组件渲染后调用
function runEffects() {
    // 执行上次的清理函数
    cleanups.forEach(cleanup => cleanup && cleanup());
    cleanups = [];

    // 执行副作用，并存储新的清理函数
    cleanups = effects.map(effect => effect());
    effects = [];
}

// 修改 render 函数以在渲染后执行副作用
export function render(element, container) {
    // ...渲染逻辑
    runEffects();
}

